package com.magiccompass.alipay.barcode.security.model;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import com.magiccompass.alipay.barcode.entity.UserInfo;

public class LoginUserModel implements UserDetails {	
	private static final long serialVersionUID = -120146130390100l;;
    private String username = "";
    private String password ="";
    private Integer loginUserId = 0;
    
    private UserInfo dbUserInfo;
    
    public LoginUserModel(String username,
			String password, Integer loginUserId, UserInfo userInfo) {
		super();
		this.username = username;
		this.password = password;
		this.loginUserId = loginUserId;
		this.dbUserInfo = userInfo;
	}
    
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return getGrantedAuthorities(getRoles(dbUserInfo.getRoleId()));       
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

	public static long getSerialversionuid() {
		return serialVersionUID;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public void setPassword(String password) {
		this.password = password;
	}
	
	public Integer getLoginUserId() {
		return loginUserId;
	}

	public void setLoginUserId(Integer loginUserId) {
		this.loginUserId = loginUserId;
	}
	
	public UserInfo getDbUserInfo() {
		return dbUserInfo;
	}

	public void setDbUserInfo(UserInfo dbUserInfo) {
		this.dbUserInfo = dbUserInfo;
	}

	private List<String> getRoles(Integer dbRoleId) {
		List<String> roles = new ArrayList<String>();		
		if (dbRoleId == 1) {
			roles.add("ROLE_ADMIN");
		}else if(dbRoleId == 2 || dbRoleId == 3){
			roles.add("ROLE_MERCHANT");
		}else if(dbRoleId == 4){
			roles.add("ROLE_MERCHANT_GROUP_ADMIN");
		}
		roles.add("ROLE_USER");			
		
		return roles;
	}
	private List<GrantedAuthority> getGrantedAuthorities(List<String> roles) {
		List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		for (String role : roles) {
			authorities.add(new SimpleGrantedAuthority(role));
		}
		return authorities;
	}
}
